package cn.tworice.blog.service.impl;

import cn.tworice.blog.dao.CommentDao;
import cn.tworice.blog.entity.SendComment;
import cn.tworice.blog.entity.SendMailDto;
import cn.tworice.blog.service.SendCommentService;
import cn.tworice.blog.utils.CoreService;
import cn.tworice.blog.utils.MailUtil;
import cn.tworice.blog.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 留言服务
 * @author 二饭
 * @email 1786705138@qq.com
 */
@Service
@Slf4j
public class SendCommentServiceImpl implements SendCommentService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisUtil redisUtil;

    // 留言交换器
    @Value("${mq.commentsExchange}")
    String commentsExchange;

    // 留言key
    @Value("${mq.commentsRoutingKey}")
    String commentsRoutingKey;

    // 发送邮箱
    @Value("${mq.mailExchange}")
    String mailExchange;

    // 发送邮箱key
    @Value("${mq.mailRoutingKey}")
    String mailRoutingKey;

    // 客户端地址
    @Value("${blog.host}")
    String host;

    @Value("${blog.mailVerifyTime}")
    Integer mailVerify;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private MailUtil mailUtil;

    /**
     * 发送消息到队列
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public RequestResult sendMessage(String message, String mail, String verify, HttpServletRequest request) {
        Boolean ify=redisUtil.mailVerify(mail,verify);
        if(ify){

            SendComment sendComment = new SendComment();
            sendComment.setMail(mail);
            sendComment.setMessage(message);
            sendComment.setTime(new Date().getTime());
            String ipAddress = CoreService.getIpAddress(request);
            sendComment.setIpAddr(ipAddress);

            String json = JSON.toJSONString(sendComment);
            rabbitTemplate.convertAndSend(commentsExchange, commentsRoutingKey, json);
            return new RequestResult(new StatusCode(200, "留言成功！"));
        }else {
            return new RequestResult(new StatusCode(204,"邮箱未通过验证！"));
        }
    }

    /**
     * 发送邮箱
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public void sendMail(String json) {
        log.info("发送消息-发送邮件");
        rabbitTemplate.convertAndSend(mailExchange,mailRoutingKey,json);
    }

    @Override
    public void sendMail(String mail, String content) throws Exception{
        SendMailDto sendMailDto = new SendMailDto();
        sendMailDto.setTo(mail);
        sendMailDto.setSubject("二饭的邮件");
        sendMailDto.setContent(content);
        mailUtil.sendMail(sendMailDto);
    }

    /**
     * 发送邮箱验证
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public void sendVerify(String mail){
        String header = "<html><head></head><body><h3 style='text-align: center;'>点击下方链接继续操作</h3><p style='text-align: center;'><a href="+host;
        // 邮件有效时间提示
        String mailVerifyTime="<p style='text-align: center;'>二饭提醒您：该邮件有效期为<a>"+(mailVerify/1000)+"</a>秒，过时需要重新验证该邮箱地址</p>";
        String footer = ">二饭的博客</a></p>"+mailVerifyTime+"</body></html>";

        String uuid = UUID.randomUUID().toString();
        String param = "comment?VerifyCode="+uuid+"&mail="+mail;

        String html=header+param+footer;
        // 以邮箱做为key，将邮箱验证信息保存到redis
        redisUtil.saveMailVerify(mail,uuid,(long)mailVerify);

        // 设置邮件内容
        SendMailDto sendMailDto = new SendMailDto();
        sendMailDto.setTo(mail);
        sendMailDto.setSubject("邮箱验证");
        sendMailDto.setContent(html);
        String json = JSON.toJSONString(sendMailDto);
        sendMail(json);
    }

    /**
     * 查询留言列表
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public RequestResult messageList(Integer pageSize, Integer pageNum) {
        RequestResult result = new RequestResult();
        try {
            List<SendComment> list = commentDao.queryMessageByPage(pageSize, pageNum);
            result.setCode(new StatusCode(200, "查询成功"));
            result.appendData("messageList", list);
        } catch (Exception exception) {
            result.setCode(new StatusCode(500, "服务器繁忙"));
            log.error("查询留言列表出现错误");
        }
        return result;
    }

    @Override
    public RequestResult messageList() {
        RequestResult result = new RequestResult();
        try {
            List<SendComment> list = commentDao.queryMessageAll();
            result.setCode(new StatusCode(200, "查询成功"));
            result.appendData("messageList", list);
        } catch (Exception exception) {
            result.setCode(new StatusCode(500, "服务器繁忙"));
            log.error("查询留言列表出现错误");
        }
        return result;
    }

    @Override
    public void delMessage(Integer id) throws Exception {
        int i=commentDao.delById(id);
        if(i==0){
            throw new Exception();
        }
    }
}
